package com.ohos.mobius.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import com.example.ohos.architecture.blueprints.todoapp.addedittask.AddEditTaskInjector;
import com.example.ohos.architecture.blueprints.todoapp.addedittask.domain.AddEditTaskEvent;
import com.example.ohos.architecture.blueprints.todoapp.addedittask.domain.AddEditTaskMode;
import com.example.ohos.architecture.blueprints.todoapp.addedittask.domain.AddEditTaskModel;
import com.example.ohos.architecture.blueprints.todoapp.addedittask.effecthandlers.AddEditTaskEffectHandlers;
import com.example.ohos.architecture.blueprints.todoapp.addedittask.view.AddEditTaskViews;
import com.example.ohos.architecture.blueprints.todoapp.data.Task;
import com.example.ohos.architecture.blueprints.todoapp.data.TaskDetails;
import com.ohos.mobius.ResourceTable;
import com.spotify.mobius.MobiusLoop;

/**
 * AddEditTaskAbilitySlice
 */
public class AddEditTaskAbilitySlice extends AbilitySlice {
    private MobiusLoop.Controller<AddEditTaskModel, AddEditTaskEvent> mController;
    private Task task;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        getWindow().setStatusBarColor(getColor(ResourceTable.Color_colorTitle));
        super.setUIContent(ResourceTable.Layout_ability_add_edit_task_activity);
        if (intent != null) {
            task = intent.getSerializableParam("taskob");
        }

        AddEditTaskViews views = new AddEditTaskViews(this, task);

        mController = AddEditTaskInjector.createController(
            AddEditTaskEffectHandlers.createEffectHandlers(getContext(), this::finishWithResultOk, views::showEmptyTaskError),
            resolveDefaultModel());

        mController.connect(views);

        findComponentById(ResourceTable.Id_iv_left).setClickedListener((component) -> {
            terminateAbility();
        });
    }

    private AddEditTaskModel resolveDefaultModel() {
        if (task != null) {
            return AddEditTaskModel.builder()
                .details(task.details())
                .mode(AddEditTaskMode.update(task.id()))
                .build();
        }

        return AddEditTaskModel.builder()
            .mode(AddEditTaskMode.create())
            .details(TaskDetails.DEFAULT)
            .build();
    }

    @Override
    public void onActive() {
        super.onActive();
        mController.start();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        mController.stop();
    }

    private void finishWithResultOk() {
        terminateAbility();
    }
}
